package com.qifei.xmlg_backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qifei.xmlg_backend.DTO.user.UserRegisterDTO;
import com.qifei.xmlg_backend.DTO.user.UserRequest;
import com.qifei.xmlg_backend.entity.ErrorCode;
import com.qifei.xmlg_backend.entity.User;
import com.qifei.xmlg_backend.exception.CustomException;
import com.qifei.xmlg_backend.mapper.UserMapper;
import com.qifei.xmlg_backend.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qifei.xmlg_backend.utils.JwtUtils;
import com.qifei.xmlg_backend.utils.Md5Utils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author user
 * @since 2025-06-15
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private final UserMapper userMapper;
    @Override
    public User findByUsername(String username) {
        return userMapper.selectOne(new QueryWrapper<User>().eq("username",username));
    }

    @Override
    public String login(UserRequest u) {
        // 查询用户是否存在 张三
        User user = findByUsername(u.getUsername());
        if (user == null) {
            throw new CustomException(ErrorCode.USER_NOT_FOUND);
        }

        // 判断密码是否正确
        String encPwd = Md5Utils.encrypt(u.getPassword());

        if (!user.getPassword().equals(encPwd)){
            throw new CustomException(ErrorCode.PASSWORD_INCORRECT);
        }

        // 登录成功 将用户数据添加到jwt中
        Map<String, Object> claims = new HashMap<>();
        claims.put("id",user.getId());
        claims.put("username",user.getUsername());
        claims.put("email",user.getEmail());
        claims.put("role",user.getRole());

        // 工具
        String jwt = JwtUtils.generateJwt(claims);

        return jwt;
    }

    @Override
    public User register(UserRegisterDTO registerDTO) {
        // 检查用户名是否已存在
        User existingUser = findByUsername(registerDTO.getUsername());
        if (existingUser != null) {
            throw new CustomException(ErrorCode.USERNAME_ALREADY_EXISTS);
        }

        // 创建新用户
        User user = new User();
        user.setUsername(registerDTO.getUsername());
        // 加密密码
        user.setPassword(Md5Utils.encrypt(registerDTO.getPassword()));
        user.setEmail(registerDTO.getEmail());
        user.setGender(registerDTO.getGender());
        // 设置默认角色
        user.setRole(registerDTO.getRole());
        // 设置默认状态为启用
        user.setStatus((byte) 1);
        // 设置创建和更新时间
        LocalDateTime now = LocalDateTime.now();
        user.setCreateTime(now);
        user.setUpdateTime(now);

        // 保存用户
        boolean success = save(user);
        if (!success) {
            throw new CustomException(ErrorCode.SERVER_ERROR);
        }

        log.info("新用户注册成功: {}", user.getUsername());
        return user;
    }

    @Override
    public Map<String, Object> getUserInfo(String token) {
        try {
            // 解析JWT令牌
            Claims claims = JwtUtils.parseJWT(token);

            // 从JWT中获取用户名
            String username = claims.get("username", String.class);

            // 根据用户名查询用户信息
            User user = findByUsername(username);
            if (user == null) {
                throw new CustomException(ErrorCode.USER_NOT_FOUND);
            }

            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("username", user.getUsername());

            // 如果用户没有头像，设置默认头像
            String avatar = user.getAvatar();
            if (avatar == null || avatar.isEmpty()) {
                avatar = "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif";
            }
            result.put("avatar", avatar);

            // 将角色转换为数组格式
            String role = user.getRole();
            List<String> roles = new ArrayList<>();
            if (role != null && !role.isEmpty()) {
                // 如果角色以role_开头，去掉前缀
                if (role.toLowerCase().startsWith("role_")) {
                    role = role.substring(5);
                }
                roles.add(role);
            } else {
                // 如果没有角色，添加默认角色
                roles.add("user");
            }
            result.put("roles", roles);

            log.info("获取用户信息成功: {}, 角色: {}", username, roles);
            return result;
        } catch (Exception e) {
            log.error("获取用户信息失败: {}", e.getMessage());
            throw new CustomException(ErrorCode.SERVER_ERROR);
        }
    }

}
